package com.sanda.androidcourse.chapter11;

import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.gson.Gson;
import com.sanda.androidcourse.R;
import com.sanda.androidcourse.chapter11.data.Response;
import com.sanda.androidcourse.chapter11.data.User;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

public class GsonParseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_gson_parse);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 从 assets 读取 JSON 数据
        String jsonString = loadJSONFromAsset();

        if (jsonString != null) {
            try {
                // 创建 Gson 对象
                Gson gson = new Gson();

                // 解析整个响应 JSON 到 Response 对象
                Response response = gson.fromJson(jsonString, Response.class);

                // 获取 status 字段
                String status = response.getStatus();
                Log.d("Gson Parsing", "Status: " + status);

                // 获取 data 数组
                List<User> users = response.getData();

                // 遍历并打印用户信息
                for (User user : users) {
                    Log.d("Gson Parsing", "User ID: " + user.getId());
                    Log.d("Gson Parsing", "Name: " + user.getName());
                    Log.d("Gson Parsing", "Age: " + user.getAge());
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 从 assets 文件夹读取 JSON 文件
    private String loadJSONFromAsset() {
        String json = null;
        try {
            AssetManager assetManager = getAssets();
            InputStreamReader inputStreamReader = new InputStreamReader(assetManager.open("data.json"));
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            json = stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }
}